import sys
from pathlib import Path

file = Path(__file__).resolve()
parent, top = file.parent, file.parents[3]

sys.path.append(str(top))
try:
    sys.path.remove(str(parent))
except ValueError: # Already removed
    pass

__package__ = 'server.report.job'

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email.utils import formataddr
from email import encoders
from server.report.config.config import Config
from server.report.utils.mysql_utils import mysql_util 
from server.report.models.model import Report, User
from server.config.log import logger


class EmailReport(object):
    def __init__(self):
        self.config = Config()
        self.sender_name = "StorageX"


    def sent_ok_email(self, report_id):

        try:

            with mysql_util.get_db() as db:
                report = db.query(Report).filter_by(id=report_id).first()
                report_name = report.report_name
                file_path = report.output_file_path
                user_id = report.user_id

                user = db.query(User).filter_by(id=user_id).first()
                user_name = user.user_name
                receiver_email = user.email

            # 创建邮件对象
            msg = MIMEMultipart()

            msg['From'] = formataddr((self.sender_name, self.config.sender_email))
            msg['Subject'] = f"《{report_name}》尽责审查报告生成通知"
            msg['To'] = receiver_email

            body = f"""
            尊敬的{user_name}：

            您好！

            根据您的发起请求，系统已完成 "{report_name}" 尽责审查报告 的自动化生成工作。
            该报告文件已作为附件添加至本邮件，请及时查阅。

            感谢您的信赖！智能尽责审查生成系统将持续为您提供高效服务。

            此致
            智能尽责审查生成系统
            """

            # 添加邮件正文
            msg.attach(MIMEText(body, 'plain', 'utf-8'))

            # 添加附件
            with open(file_path, "rb") as attachment:
                part = MIMEBase('application', 'octet-stream')
                part.set_payload(attachment.read())

            encoders.encode_base64(part)
            part.add_header(
                'Content-Disposition',
                f'attachment; filename="{file_path.split("/")[-1]}"'
            )
            msg.attach(part)

            self.send_email(msg, receiver_email)
        except Exception as e:
            logger.error(f"发送 OK 邮件时发生错误: {e}")


    def sent_error_email(self, error_msg, report_id):
        try:

            with mysql_util.get_db() as db:
                report = db.query(Report).filter_by(id=report_id).first()
                user_id = report.user_id

                user = db.query(User).filter_by(id=user_id).first()
                receiver_email = user.email

            # 创建邮件对象
            msg = MIMEMultipart()

            msg['From'] = formataddr((self.sender_name, self.config.sender_email))
            msg['Subject'] = f"尽责系统-{report_name}-生成错误"
            msg['To'] = receiver_email

            # 添加邮件正文
            msg.attach(MIMEText(error_msg, 'plain', 'utf-8'))

            self.send_email(msg, receiver_email)
        except Exception as e:
            logger.error(f"发送 ERROR 邮件时发生错误: {e}")


    def send_email(self, msg, receiver_email):
        try:
            # 建立SMTP连接
            server = smtplib.SMTP_SSL(self.config.smtp_server, self.config.smtp_port)

            # 登录邮箱
            server.login(self.config.sender_email, self.config.password)

            # 发送邮件
            server.sendmail(self.config.sender_email, receiver_email, msg.as_string())

            # 关闭连接
            server.quit()

            logger.info("邮件发送成功！")
        except smtplib.SMTPAuthenticationError:
            logger.error("认证失败：请检查邮箱和密码是否正确")
        except smtplib.SMTPException as e:
            logger.error(f"邮件发送失败: {e}")



if __name__ == "__main__":
    email_report = EmailReport()

    email_report.sent_ok_email(15)


